package cn.hiapi.shopkeeper.task;

import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.entity.order.ActivityOrderLog;
import cn.hiapi.shopkeeper.enums.OrderLogType;
import cn.hiapi.shopkeeper.enums.OrderStatus;
import cn.hiapi.shopkeeper.service.activity.ActivityService;
import cn.hiapi.shopkeeper.service.order.ActivityOrderLogService;
import cn.hiapi.shopkeeper.service.order.ActivityOrderService;
import cn.hiapi.shopkeeper.task.abs.AbsTaskService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author AdinZ
 * @date 2023/1/2 23:35
 */
@Component
public class OrderTaskService extends AbsTaskService {

    public OrderTaskService(DispatchContext dispatchContext) {
        super(dispatchContext);
    }

    /**
     * 监听活动结束任务
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void orderClose() {
        //结束的活动列表
        List<ActivityOrder> list = this.dispatchContext.getServiceOne(ActivityOrderService.class).findList(new QueryWrapper()
                .eq("status", OrderStatus.WAIT_PAY).le("expire", System.currentTimeMillis()));

        for (ActivityOrder order : list) {

            if (order.getStatus() != OrderStatus.WAIT_PAY) continue;
            if (order.getExpire() > System.currentTimeMillis()) continue;

            this.dispatchContext.getServiceOne(ActivityOrderService.class).closeOrder(order);

            ActivityOrderLog t = new ActivityOrderLog();
            t.setOid(order.getId());
            t.setUserType("SYSTEM_TASK");
            t.setRemark("订单超时关闭订单");
            t.setType(OrderLogType.CANCEL);
            this.dispatchContext.getServiceOne(ActivityOrderLogService.class).save(t);
        }

    }



}
